<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-5-13
 * Time: 上午10:47
 * To change this template use File | Settings | File Templates.
 */
namespace pft;
class notice {

    /**
     * 添加通知
     *
     * @param $title 通知标题
     * @param $content 通知内容
     * @param $status  通知状态
     * @param $px 排序值如果为9999表示为管理员发送！
     * @param $apply_did 发布人ID,如果是系统
     * @param int $sms 是否发短信1发送0不发送
     * @param string $et 通知截止时间
     * @param string $lnkprods 关联产品
     * @param Member\MemberAccount $member 会员类的实例
     * @param integer $uid 会员表ID
     * @return array
     */
    public function AddNotice($title, $content, $status, $px,
                              $apply_did, $sms=0, $et='',$lnkprods='',
                              \pft\Member\MemberAccount $member=null, $uid=null)
    {
        $byAdmin = $apply_did == 1 ? true : false;
        if ($apply_did!=7517 || !$byAdmin || $apply_did!=22009) {
            if(!empty($uid)) {
                //发送给指定人物
                $myDistors =$member->GetMobileWithId($uid);
            }
            else {
                $myDistors = $member->GetDistorByApplyerId();//获取我的分销商
            }
//            print_r($myDistors);
//            exit;
            //var_dump($myDistors);
            if(!count($myDistors)) {
                return array(
                    'errcode'=>1001,
                    'msg'=>'您没有下级分销商，无法发送通知。发布通知失败'
                );
            }
            $sendto = array_keys($myDistors);
            if($sms) {
                $soap = \SoapInit::GetSoapInside();
                $send_content = "[{$title}]{$content}【票付通】";

                if($px!=9999) {
                    $len = mb_strlen($content,'utf-8');
                    $sms_count = ceil($len / 67);
                    //获取admin为供应商配置的短信费
                    $fees = $member->GetFeesCfg();
                    $sms_fee = $fees['fee_sms']/100;
                    //短信计费
                    $sms_money_total = $sms_count * count($sendto) * $sms_fee * 100;
                    //查看资金账户余额
                    $money_l = $member->ShowBalance($apply_did, $soap);
                    if($sms_money_total > $money_l) {
                        return array(
                            'errcode'=>1002,
                            'msg'=>'账户余额不足，无法发送短信！请充值。'
                        );
                    }
                }
            }
        }

        $px2 = $px > 127 || $byAdmin ? 100 : 0;
        $str = <<<SQL
      INSERT INTO `uu_notice` (`title`, `content`, `btime`, `etime`, `status`,
      `ntype`, `px`,`adminid`,`sms_notify`,`lnkprods`)
      VALUES ('{$title}', '{$content}', now(), '{$et}',
      {$status}, '0', {$px2},{$apply_did},'{$sms}','{$lnkprods}')
SQL;
//        echo $str;
        $GLOBALS['le']->query($str);
        $lastid = mysql_insert_id();
        //添加数据到扩展表
        if (count($sendto)) {
            $sr = $this->SentNotice($sendto, $lastid);
            //是否发送短信
            if($sr && $sms) {
                //若不是系统通知，从资金账户扣钱
                if($px!=9999) {
                    $kq_r = $soap->PFT_Member_Fund_Modify($apply_did, $apply_did,
                        $sms_money_total, 1, 0, '', 8, 0);
                    if($kq_r!=100) return array('errcode'=>1001,'msg'=>'发布通知发生错误,扣费失败；短信没有发送');
                }
                $mobiles = array_values($myDistors);
                //发送短信
                $this->_SendSms($lastid, $send_content, $mobiles, $soap);
            }
            if(!$sr) {
                return array('errcode'=>1001,'msg'=>'发布通知发生错误');
            }
        }

        return array('errcode'=>1000,'msg'=>'发布成功');
    }

    const SEND = 1;
    const RECIVE = 2;
    const COUNT = 1;

    /**
     * 获取通知列表
     *
     * @param int $type notice::SEND[发出的通知],notice::RECIVE[接收的通知]
     * @param array $params array('adminid'=>会员ID,'rs'=>'阅读状态',
     *                            'limit'  => '分页起始位置','offset' => '条数')
     * @param bool $count 是否返回统计条数 TRUE返回统计条数
     * @return array
     */
    public function GetNoticeList($type, $params, $count=false)
    {
        $where = ' WHERE 1=1';
        $rs = $type==self::RECIVE ? ',e.status as rstate' : '';
        $str = "SELECT n.id,n.`title`, n.`content`, n.`btime`,n.`status`,"
            ."n.`adminid`,n.`ntype`,n.`px`,n.sms_notify,m.dname {$rs} FROM uu_notice n "
            ." LEFT JOIN pft_member m ON m.id=n.adminid ";
        $str_l = '';
        switch($type) {
            case self::SEND:
                $where .= " AND n.adminid={$params['adminid']} AND n.status<>2" ;
                break;
            case self::RECIVE:
                $str_l .= ", uu_notice_ext e ";
                $where .= " AND e.nid=n.id AND e.did={$params['adminid']} "
                         . (isset($params['rs']) && $params['rs']!=3
                         ? " AND e.status={$params['rs']}":' AND e.status<>2');
                $where .= " AND n.`status`=1";
                break;
            default:
                break;
        }
        //$where .= " AND n.`status`=1";
        if($count) {
            $str = "SELECT COUNT(*) AS c FROM uu_notice n" .$str_l . $where;
            $GLOBALS['le']->query($str);
            $GLOBALS['le']->fetch_assoc();
            return $GLOBALS['le']->f('c');
        }
        $qs = $str.$str_l.$where;
        $qs .= " ORDER BY n.btime DESC LIMIT {$params['limit']},{$params['offset']}";
        //echo $qs;
        $GLOBALS['le']->query($qs);
        $noticeList = array();
        while($list = $GLOBALS['le']->fetch_assoc()) {
            $noticeList[] = $list;
        }
        return $noticeList;
    }

    /**
     * 获取单条通知
     *
     * @param $nid 通知Id
     * @param $uid 会员ID
     * @param $db
     * @return mixed
     */
    public function GetNoticeOne($nid, $uid, $db=null) {
        $str = "SELECT n.id,n.`title`,n.`content`,n.`btime`,n.`etime`,"
            . "n.`ntype`,n.adminid,n.status,n.sms_notify,"
            . "n.px,n.lnkprods FROM uu_notice n"
            . " WHERE n.id={$nid} AND n.adminid={$uid} LIMIT 1";
        if (is_null($db)) {
            $db = $GLOBALS['le'];
        }
        $db->query($str);
        return  $db->fetch_assoc();
    }

    /**
     * 阅读通知（将阅读状态更新）
     *
     * @param $nid 通知ID
     * @param $did 会员ID
     * @return mixed
     */
    public function ReadNotice($nid,$did) {
        $str = "SELECT n.id,n.title, n.content, n.btime,n.px,n.lnkprods,"
            ."e.id as eid,e.`status` as read_status,adminid FROM uu_notice n ";
        $str .= " LEFT JOIN uu_notice_ext e ";
        $str .= "ON (e.nid=n.id  AND e.did={$did}) WHERE n.id={$nid} AND n.status=1";
        $GLOBALS['le']->query($str);
        $res = $GLOBALS['le']->fetch_assoc();
        //print_r($res);
        if(!$res['eid']) {
            $str_insert = "INSERT INTO uu_notice_ext (nid,did,status) VALUES ";
            $str_insert .= "({$nid},{$did},1)";
//            echo $str_insert;
            $GLOBALS['le']->query($str_insert);
        }
        elseif(!$res['read_status']) {
            $str = "UPDATE uu_notice_ext SET `status`=1 WHERE nid={$nid} AND did={$did}";
           // echo $str;
            $GLOBALS['le']->query($str);
        }
        if(isset($_SESSION['unreadmsg']) && $_SESSION['unreadmsg']>0) {
            $_SESSION['unreadmsg'] -= 1;
        }
        return $res;
    }
    /**
     * 发送通知给各个分销商
     *
     * @param array $idList 分销商ID
     * @param $nid 消息ID
     * @param int $status 阅读状态
     * @return int
     */
    public function SentNotice(Array $idList,$nid, $status=0) {
        if(!count($idList)) return 0;
        $str = "INSERT INTO uu_notice_ext (nid,did,status) VALUES ";
        foreach($idList as $id) {
            $str .= "({$nid},{$id},{$status}),";
        }
        $str = rtrim($str,',');
//        echo $str;
        if($GLOBALS['le']->query($str)) {
            return 1;
        }
        return 0;
    }

    /**
     * 管理员通知审核，
     *  a.根据状态判定是否要删除通知从表的记录
     *  b.判断是否需要发送短信
     *
     * @param $nid 通知ID
     * @param $status 状态 1通过2拒绝3删除[4物理删除]
     * @return int
     */
    public function SetNoticeStatusByAdmin($nid, $status) {
        $notice_id = is_array($nid) ? implode(',',$nid) : rtrim($nid, ',');
        if($status==4) {
            $str = "DELETE FROM uu_notice WHERE id IN ($notice_id)";
        }
        else {
            $str = "UPDATE uu_notice SET status={$status} WHERE id IN ($notice_id)";
        }
        $GLOBALS['le']->query($str);
        if($status!=1) {
            $str_rm = "DELETE FROM uu_notice_ext WHERE nid IN ($notice_id)";
            $GLOBALS['le']->query($str_rm);
        }
        return 1;
    }

    /**
     * 发送短信并记录发送的手机号码（电话号码以160个为一组，分批处理数据）
     *
     * @param integer $nid 通知ID
     * @param string $nc  通知内容
     * @param array $phones 通知手机
     * @param \SoapClient $soap
     * @param bool $resend 是否重发
     * @return array|int
     */
    public function _SendSms($nid, $nc, $phones=array(),\SoapClient $soap, $resend=false) {
        $length = count($phones);
        $f = ceil($length/99);
        if(!$f) {
            return 0;
        }
        //echo $f;
        $ait = new \ArrayIterator($phones);
        $str_insert = "INSERT INTO uu_notice_sms (nid,phones) VALUES";
        $values = '';
        $send_res = array();
        for($i=0;$i<$f; $i++) {
            $offset = $i*99;
            $lit = new \LimitIterator($ait, $offset, 99);
            $tels =  implode(',', iterator_to_array($lit));
            $send_res[] = $soap->Send_SMS_G($tels, $nc);
            if(strlen($tels)>0) {
                $values .= "($nid,'{$tels}'),";
            }
        }
        if( !$resend && strlen($values)>0 ) {
            $values = rtrim($values,',');
            $GLOBALS['le']->query($str_insert . $values);
        }
        //print_r($send_res);
        return $send_res;
    }

    /**
     * 设置消息已读、未读状态
     *
     * @param int $nid 消息ID
     * @param int $did 分销商ID
     * @param int $status,0未读1已读2删除4删除（）
     * @param int $dtype 会员类型0供应商1分销商
     * @return integer
     */
    public function SetNoticeStatus($nid, $did, $status=1, $dtype=1) {
        if(is_array($nid)) {
            $id = implode(',', $nid);
        }
        else {
            $id = rtrim(',', $nid);
        }
        if(!$status) {
            $str_rm_main = "UPDATE uu_notice SET `status`=2 WHERE id IN({$id}) AND adminid={$did}";
            //echo $str_rm_main;
            $GLOBALS['le']->query($str_rm_main);
        }
        $str = "UPDATE uu_notice_ext SET `status`={$status} WHERE nid IN({$id}) AND did={$did}";
        $GLOBALS['le']->query($str);
        return 1;
    }

    /**
     * 统计会员未读消息数
     *
     * @param $mid 会员id
     * @param $db  mysql实例
     * @return mixed
     */
    static function UnReadCount($mid, $db)
    {
        $sql = <<<SQL
        SELECT COUNT(*) as c FROM uu_notice_ext e
        LEFT JOIN uu_notice m ON m.id=e.nid
        WHERE e.did=$mid AND e.status=0
        AND m.status=1
SQL;
        $db->query($sql);
        $db->fetch_assoc();
        return $db->f('c');
    }
}#EOF CLASS